package com.ltv.xiangqibook.dbtool;

import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.ltv.xiangqibook.common.GameIDCreator;
import com.ltv.xiangqibook.common.XiangQiBookConfiguration;

public class DirectoryGenerator {
    private static final Logger logger = LogManager.getLogger(DirectoryGenerator.class);

    static Connection con = null;
    static PreparedStatement insertDirectories = null;
    static PreparedStatement deleteDirectories = null;

    static String insertQuery = "insert into directories(full_path, game_id_list) values (?, ?)";
    static String deleteQuery = "delete from directories";
    
    static List<String> directoryKeys = new ArrayList<String>();
    static Map<String, List<String>> directories = new HashMap<String, List<String>>();

    public static void main(String[] args) {
        logger.info("Start generating directories...");
        try {
            String xiangqiBookHome = args[0];
            XiangQiBookConfiguration.getInstance().loadConfiguration(xiangqiBookHome + "/" + XiangQiBookConfiguration.CONFIG_FILE_NAME);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            System.exit(1);
        }

        try {
            Class.forName("com.mysql.jdbc.Driver");
            String dbURL = "jdbc:mysql://" + XiangQiBookConfiguration.getInstance().getDBHost();
            dbURL += ":" + XiangQiBookConfiguration.getInstance().getDBPort();
            dbURL += "/" + XiangQiBookConfiguration.getInstance().getDBName();
            dbURL += "?useEncoding=true&characterEncoding=UTF-8";

            String dbUser = XiangQiBookConfiguration.getInstance().getDBUser();
            String dbPassword = XiangQiBookConfiguration.getInstance().getDBPassword();

            con =DriverManager.getConnection (dbURL, dbUser, dbPassword);
            con.setAutoCommit(false);
            insertDirectories = con.prepareStatement(insertQuery);
            deleteDirectories = con.prepareStatement(deleteQuery);

            deleteDirectories.execute();

            initDirectoryKeys(XiangQiBookConfiguration.getInstance().getBookLocalLocation());
            
            for (String key : directoryKeys) {
            	directories.put(key, new ArrayList<String>());
            	putAllGameIDIntoDirMap(key, key);
            }
            
            for (String key : directories.keySet()) {
            	List<String> gameIdList = directories.get(key);
            	
            	StringBuffer gameIds = new StringBuffer();
            	gameIds.append("|");
            	for (String gameId : gameIdList) {
            		gameIds.append(gameId + "|");
            	}
            	
            	insertDirectories.setString(1, key);
            	insertDirectories.setString(2, gameIds.toString());
            	
            	insertDirectories.executeUpdate();
            }

            con.commit();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            try {
                con.rollback();
            } catch (SQLException e1) {
                logger.error(e.getMessage(), e);
            }
        } finally {
            if (deleteDirectories != null) {
                try {
                    deleteDirectories.close();
                } catch (SQLException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (insertDirectories != null) {
                try {
                    insertDirectories.close();
                } catch (SQLException e) {
                    logger.error(e.getMessage(), e);
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
        
        logger.info("End generating directories.");

    }

    public static void initDirectoryKeys(String path) throws Exception {
    	File root = new File( path );
        File[] list = root.listFiles();
        Arrays.sort(list);

        for ( File f : list ) {
            if ( f.isDirectory()) {
            	if (f.getName().indexOf(".svn") == -1) {
            		directoryKeys.add(f.getAbsolutePath());
            		initDirectoryKeys(f.getAbsolutePath());
            	}
            }
        }
    }
    
    private static void putAllGameIDIntoDirMap(String keyMap, String path) throws Exception {
    	File root = new File( path );
        File[] list = root.listFiles();
        Arrays.sort(list);

        for ( File f : list ) {
            if ( f.isDirectory()) {
            	if (f.getName().indexOf(".svn") == -1) {
            		putAllGameIDIntoDirMap( keyMap, f.getAbsolutePath() );
            	}
            }
            else {
            	if (f.getName().endsWith(".pgn")) {
            		directories.get(keyMap).add(GameIDCreator.getGameID(f));
            	}
            }
        }
    	
    }

}
